/*
 * Copyright 2022-2025 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springframework.data.relational.core.conversion;

import org.springframework.data.relational.core.mapping.RelationalPersistentEntity;
import org.springframework.data.relational.core.mapping.RelationalPersistentProperty;

/**
 * Enumeration describing the source of a value for an id property.
 *
 * @author Chirag Tailor
 * @since 2.4
 */
public enum IdValueSource {

	/**
	 * The id value is provided on the instance.
	 */
	PROVIDED,

	/**
	 * The id value is generated by the store.
	 */
	GENERATED,

	/**
	 * There is no id property, and therefore no id value source.
	 */
	NONE;

	/**
	 * Returns the appropriate {@link IdValueSource} for the instance: {@link IdValueSource#NONE} when the entity has no
	 * id property, {@link IdValueSource#PROVIDED} when the value of the id property is not null and when it is a
	 * primitive type, not zero, and {@link IdValueSource#GENERATED} otherwise.
	 */
	public static <T> IdValueSource forInstance(Object instance, RelationalPersistentEntity<T> persistentEntity) {

		Object idValue = persistentEntity.getIdentifierAccessor(instance).getIdentifier();
		RelationalPersistentProperty idProperty = persistentEntity.getIdProperty();
		if (idProperty == null) {
			return IdValueSource.NONE;
		}
		boolean idPropertyValueIsSet = idValue != null && //
				(idProperty.getType() != int.class || !idValue.equals(0)) //
				&& (idProperty.getType() != long.class || !idValue.equals(0L));
		if (idPropertyValueIsSet) {
			return IdValueSource.PROVIDED;
		} else {
			return IdValueSource.GENERATED;
		}
	}
}
